import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { ApiCodeEnum } from 'src/enum/api-code.enum';
import { RedisUtils } from 'src/utils/redis.utils';
import { ResultVo } from 'src/vo/common/result.vo';

@Injectable()
export class LoginMiddleware implements NestMiddleware {
  constructor(private readonly redis: RedisUtils) { }

  async use(req: Request, res: Response, next: NextFunction) {
    console.log('登陆中间件:token', req.url, req.headers.token);
    if (req.url.includes("checkHealth")) {
      return res.json(ResultVo.success())
    }

    const token = req.headers.token + ""
    const whitelist = [
      "/member/login", "/member/getCode", "/navConfig/queryAll", "/classification/queryAll",
      "/product/queryProductsByPage", "/product/queryDetail"
    ]
    const isEnable = true
    if (isEnable && !whitelist.includes(req.url)) {
      if (!token) {
        console.log("token参数必传");

        return res.json(ResultVo.exception(ApiCodeEnum.TOKEN_EXPIRE))
      }
      // 验证token
      const userStr = await this.redis.get(token)
      console.log("当前登陆用户", userStr);
      if (!userStr) return res.json(ResultVo.exception(ApiCodeEnum.TOKEN_EXPIRE))
      // 设置用户id
      req.body.userId = JSON.parse(userStr).id
      req.headers.currentUser = userStr
    }
    next();
  }
}
